/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package src.Ultil;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.DomAttr;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.DomText;
import com.gargoylesoftware.htmlunit.html.HtmlListItem;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.XMLEvent;
import org.w3c.dom.Element;
import src.bean.XpathBean;
import src.pojo.Catagory;
import src.pojo.Product;
import src.pojo.Products;

/**
 *
 * @author LeMinh
 */
public class XMLUltilities {

//    public static void crappingWebsite(String urlWeb, String sourceXpath, String realPath) throws IOException, FileNotFoundException, XMLStreamException {
//
//
//        //define browser client
//        WebClient webclient = new WebClient(BrowserVersion.CHROME);
//        //define webpage to get
//        HtmlPage page = webclient.getPage(urlWeb);
//        XpathBean xpath = readXpathFromXML(sourceXpath);
//        //get link url of catagoryLinks
//        List<DomNode> catagoryLinks = (List<DomNode>) page.getByXPath(xpath.getMenu());
//        List<Catagory> catagories = new ArrayList<Catagory>();
//        for (DomNode domNode : catagoryLinks) {
//            Element d = (Element) domNode;
//            String link = d.getAttribute("href");
//            Catagory cate = new Catagory(domNode.asText(), link, urlWeb);
//            catagories.add(cate);
//        }
//        Products productList = new Products();
//        int count = 0;
//        for (Catagory catagory : catagories) {
//            System.out.println("Catagory Name: " + catagory.getCatagoryName());
//            HtmlPage productPage = webclient.getPage(catagory.getCatagoryLink());
//            System.out.println(catagory.getCatagoryLink());
//            DomAttr a = new DomAttr(page, null, "href", catagory.getCatagoryLink(), true);
//            System.out.println("Pagging xpath: " + xpath.getContent() + xpath.getPagging());
//            System.out.println("Pagging xpath: " + xpath.getPagging());
//            System.out.println("Div items: " + xpath.getContent() + xpath.getDivItem());
//            List<DomAttr> link = (List<DomAttr>) productPage.getByXPath(xpath.getContent() + xpath.getPagging());
//            link.add(a);
//            for (DomAttr st : link) {
//                System.out.println("size: " + link.size() + ", Link: " + st.getValue());
//                HtmlPage pd = webclient.getPage(st.getValue());
//                List<HtmlListItem> productDivs = (List<HtmlListItem>) pd.getByXPath(xpath.getContent() + xpath.getDivItem());
//                for (HtmlListItem div : productDivs) {
//                    count++;
//                    DomAttr productLink = div.getFirstByXPath(xpath.getProductLink());
//                    //System.out.println("Product Link: "+ productLink.getTextContent());
//                    DomAttr imgLink = div.getFirstByXPath(xpath.getImgLink());
//                    //System.out.println("ImgLink: "+ imgLink.getTextContent());
//                    DomText productName = div.getFirstByXPath(xpath.getProductName());
//                    //System.out.println("Product Name: "+ productName.asText());
//                    DomText producPrice = div.getFirstByXPath(xpath.getPrice());
//                    //System.out.println("Price: "+producPrice.asText());
//                    try {
//                        Product product = new Product(productName.asText(), producPrice.asText(), imgLink.getValue(), productLink.getValue(), "");
//                        //Product product = new Product("NhutLM", "NhutLM", "NhutLM", "NhutLM");
//                        productList.getProduct().add(product);
//                    } catch (NullPointerException e) {
//                        System.out.println("Error: " + e.getCause());
//                    }
//                }
//            }
//            System.out.println(count);
//        }
//        System.out.println("Begin parse to XML");
//        createXMLFromObject(productList, realPath + "WEB-INF/products.xml");
//        System.out.println("End Parse");
//    }

    public static void createXMLFromObject(Products listPro, String nameXML) {
        try {
            JAXBContext ctx = JAXBContext.newInstance(Products.class);
            Marshaller mar = ctx.createMarshaller();
            mar.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            mar.marshal(listPro, new File(nameXML));
        } catch (JAXBException ex) {
            Logger.getLogger(XMLUltilities.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("Created xml");
    }

    public static int convertToInt(String st) {

        char[] c = st.toCharArray();
        String result = "";
        for (int i = 0; i < c.length; i++) {
            try {
                result += Integer.parseInt(Character.toString(c[i]));
            } catch (NumberFormatException e) {
                System.out.println("Deo parse dc!!!");
            }
        }
        return Integer.parseInt(result);
    }

    public static XpathBean readXpathFromXML(String urlXML) throws FileNotFoundException, XMLStreamException {
        FileInputStream inputFile = null;
        XpathBean xpath = new XpathBean();
        XMLInputFactory xif = XMLInputFactory.newFactory();
        inputFile = new FileInputStream(urlXML);
        XMLEventReader evenReader = xif.createXMLEventReader(inputFile);
        while (evenReader.hasNext()) {
            XMLEvent event = evenReader.nextEvent();
            if (event.isStartElement()) {
                if (event.asStartElement().getName().getLocalPart().equals("menu")) {
                    event = evenReader.nextEvent();
                    xpath.setMenu(event.asCharacters().getData());
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("divItem")) {
                    event = evenReader.nextEvent();
                    xpath.setDivItem(event.asCharacters().getData());
                    continue;
                }
                Iterator iter = event.asStartElement().getAttributes();
                while (iter.hasNext()) {
                    Attribute attr = (Attribute) iter.next();
                    xpath.setPagging(attr.getValue());
                }
                if (event.asStartElement().getName().getLocalPart().equals("content")) {
                    event = evenReader.nextEvent();
                    xpath.setContent(event.asCharacters().getData());
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("productLink")) {
                    event = evenReader.nextEvent();
                    xpath.setProductLink(event.asCharacters().getData());
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("imgLink")) {
                    event = evenReader.nextEvent();
                    xpath.setImgLink(event.asCharacters().getData());
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("productName")) {
                    event = evenReader.nextEvent();
                    xpath.setProductName(event.asCharacters().getData());
                    continue;
                }
                if (event.asStartElement().getName().getLocalPart().equals("price")) {
                    event = evenReader.nextEvent();
                    xpath.setPrice(event.asCharacters().getData());
                    continue;
                }
            }
        }
        return xpath;
    }
    
}
